/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import Negocio.Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author JAVA
 */
public class Registro extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            Date fechaAlta = new Date();//la fecha de alta
            
            String nombre = request.getParameter("nombre");
            String apellidos = request.getParameter("apellidos");
            String ano = request.getParameter("ano");
            String mes = request.getParameter("mes");
            String dia = request.getParameter("dia");            
            String emailr1 = request.getParameter("emailr1");
            String emailr2 = request.getParameter("emailr2");
            String password = request.getParameter("password");  
            String sexo = request.getParameter("sexo");
            String ciudad = request.getParameter("ciudad");
            
            //String ruta = getServletContext().getContextPath();//la ruta solo para cuando sea con el sendredirect
            
            //comprobacion ningun campo vacio
            if(nombre.equals("") || apellidos.equals("") || emailr1.equals("") || emailr2.equals("") || password.equals("") || dia.equals("")||ano.equals("")||mes.equals("")||ciudad.equals("")){                                          
                request.setAttribute("mensaje", "Rellena todos los campos del formulario por favor");                
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }  
            
            //HAY QUE COMPROBAR QUE EL EMAIL NO ESTÉ YA EN LA BASE DE DATOS
            
            if(!emailr1.equals(emailr2)){
                request.setAttribute("mensaje", "Introduce el email en los dos campos");                
                request.getRequestDispatcher("index.jsp").forward(request, response);  
            } 
            else{
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                
                String fechaN = request.getParameter("ano")+"-"+request.getParameter("mes")+"-"+request.getParameter("dia");
                Date fechaNacimiento=dateFormat.parse(fechaN);
                sexo=sexo.substring(0,1);
                
                Usuario usuario = new Usuario(nombre,apellidos,emailr1,password, fechaNacimiento,sexo, ciudad, fechaAlta, true);
                
                usuario.crearUsuario();
                
                HttpSession sesion = request.getSession();  
                
                sesion.setAttribute("usuario", usuario);
                sesion.setAttribute("usuarioShow", usuario);
                
                response.sendRedirect("perfil.jsp"); 
            }
             
            
            
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(Registro.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (ParseException ex) {
            Logger.getLogger(Registro.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
